const request = require('request');
const { MediaCheck, User, SysConfig } = require('../db');
const { randomString } = require('../utils');
const dayjs = require('dayjs');
const utc = require('dayjs/plugin/utc');
const timezone = require('dayjs/plugin/timezone');
dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.tz.setDefault('PRC');
// const cloud = require('wx-server-sdk');
// cloud.init({
//   env: cloud.DYNAMIC_CURRENT_ENV,
// });
module.exports = {
  securityController(app) {
    // 校验媒体数据（异步）
    app.post('/api/security/mediaCheck', async (req, res) => {
      const ignorePicCheckSysConfig = (await SysConfig.findAll({ where: { key: 'IGNORE_PIC_CHECK' } }))?.map(_ => _.dataValues)?.[0];
      if (ignorePicCheckSysConfig.value === '1') {
        res.send({
          code: 200,
          data: {
            errmsg: 'ok',
            traceId: 'xxx',
          },
          msg: 'success',
        });
        return;
      }
      const openId = req.headers['x-wx-openid'] || req.body?.openId;
      const { url = '', type = 2, scene = 1 } = req.body;
      console.log('🚀 ~ /api/security/mediaCheck', { openId, url, type, scene });
      const api = `http://api.weixin.qq.com/wxa/media_check_async`;
      request(api, {
        method: 'POST',
        body: JSON.stringify({
          'media_url': url,
          media_type: type,
          'version': 2,
          scene,
          openid: openId,
        }),
        headers: {
          'Content-Type': 'application/json',
        },
      }, (err, resp, body) => {
        console.log('🚀 ~ err, resp', err);
        const rlt = JSON.parse(resp.body || '{}');
        console.log('🚀 ~ rlt', rlt);
        try {
          if (rlt.errcode === 0) {
            res.send({
              code: 200, data: {
                errmsg: rlt.errmsg,
                traceId: rlt.trace_id,
              }, msg: 'success',
            });
            // const lastLoginTime = dayjs.tz().toDate();
            MediaCheck.create({
              traceId: rlt.trace_id,
              openId,
              result: '',
              url,
              expired: dayjs.tz().add(10, 'minute').toDate(), // 10分钟后过期
            });
          } else {
            res.send({ code: rlt.errcode, data: rlt.errmsg, msg: 'fail' });
          }
        } catch (error) {
          res.send({ code: -1, error, msg: '媒体校验失败' });
        }
      });
    });
    // 获取媒体校验结果
    app.get('/api/security/getMediaCheckResult', async (req, res) => {
      const openId = req.headers['x-wx-openid'] || req.query?.openId;
      if (!openId) {
        res.send({ code: -1, msg: '缺少参数openId' });
        return;
      }
      const { traceId } = req.query;
      try {
        const ignorePicCheckSysConfig = (await SysConfig.findAll({ where: { key: 'IGNORE_PIC_CHECK' } }))?.map(_ => _.dataValues)?.[0];
        if (ignorePicCheckSysConfig.value === '1') {
          res.send({
            code: 200,
            data: {
              id: new Date().getTime(),
              openId: openId,
              result: {
                result: { 'suggest': 'pass', 'label': 100 },
                trace_id: 'xxx',
              },
              traceId: 'xxx',
            },
            msg: 'success',
          });
          return;
        }
        const rlt = await MediaCheck.findAll({
          where: { traceId },
        });
        const data = rlt?.[0];
        data.result = data.result ? JSON.parse(data.result) : '';
        res.send({
          code: 200,
          data,
          msg: 'success',
        });
      } catch (error) {
        res.send({ code: -1, error, msg: '获取媒体校验结果失败' });
      }
    });
    // 校验文本
    app.post('/api/security/msgSecCheck', async (req, res) => {
      const openId = req.headers['x-wx-openid'] || req.body?.openId;
      const { content = '', scene = 1, title = '', nickname = '', signature = '' } = req.body;
      console.log('🚀 ~ /api/security/msgSecCheck', { openId, content, scene });
      const api = `http://api.weixin.qq.com/wxa/msg_sec_check`;
      request(api, {
        method: 'POST',
        body: JSON.stringify({
          content,
          openid: openId,
          'version': 2,
          scene,
          title,
          nickname,
          signature,
        }),
        headers: {
          'Content-Type': 'application/json',
        },
      }, (err, resp, body) => {
        console.log('🚀 ~ err, resp', err);
        const rlt = JSON.parse(resp.body || '{}');
        console.log('🚀 ~ rlt', rlt);
        const { detail, result } = rlt;
        try {
          if (rlt.errcode === 0) {
            res.send({
              code: 200, data: {
                detail, result,
              }, msg: 'success',
            });
          } else {
            res.send({ code: rlt.errcode, data: rlt.errmsg, msg: 'fail' });
          }
        } catch (error) {
          res.send('get phone failed');
        }
      });
    });
    // app.post('/api/security/mediaCheck', async (req, res) => {
    //   const openId = req.headers['x-wx-openid'] || req.body?.openId;
    //   const { url = '', type = 2, scene = 1 } = req.body;
    //   console.log('🚀 ~ /api/security/mediaCheck', { openId, url, type, scene });
    //   try {
    //     console.log('🚀 ~ cloud.openapi', cloud.openapi);
    //     console.log('🚀 ~ cloud.openapi.security', cloud.openapi.security);
    //     console.log('🚀 ~ cloud.openapi.security.mediaCheckAsync', cloud.openapi.security.mediaCheckAsync);
    //     const rlt = await cloud.openapi.security.mediaCheckAsync({
    //       'media_url': url,
    //       media_type: type,
    //       'version': 2,
    //       scene,
    //       openid: openId,
    //     });
    //     console.log('🚀 ~ 【cloud.openapi.security.mediaCheckAsync】rlt.trace_id', rlt.trace_id);
    //     if (rlt.errcode === 0) {
    //       res.send({ code: 200, data: rlt.errmsg, msg: 'success' });
    //     } else {
    //       res.send({ code: rlt.errcode, data: rlt.errmsg, msg: 'fail' });
    //     }
    //   } catch (e) {
    //     res.send({ code: -10001, data: '系统异常', msg: e });
    //   }
    // });
    // app.post('/api/security/msgSecCheck', async (req, res) => {
    //   const openId = req.headers['x-wx-openid'] || req.body?.openId;
    //   const { content = '', scene = 1, title = '', nickname = '', signature = '' } = req.body;
    //   console.log('🚀 ~ /api/security/msgSecCheck', { openId, content, scene });
    //   try {
    //     console.log('🚀 ~ cloud.openapi', cloud.openapi);
    //     console.log('🚀 ~ cloud.openapi.security', cloud.openapi.security);
    //     console.log('🚀 ~ cloud.openapi.security.msgSecCheck', cloud.openapi.security.msgSecCheck);
    //     const rlt = await cloud.openapi.security.msgSecCheck({
    //       content,
    //       openid: openId,
    //       'version': 2,
    //       scene,
    //       title,
    //       nickname,
    //       signature,
    //     });
    //     if (rlt.errcode === 0) {
    //       res.send({ code: 200, data: rlt.errmsg, msg: 'success' });
    //     } else {
    //       res.send({ code: rlt.errcode, data: rlt.errmsg, msg: 'fail' });
    //     }
    //   } catch (e) {
    //     res.send({ code: -10001, data: '系统异常', msg: e });
    //   }
    // });
  },
};
